const args = require('minimist')(process.argv.slice(2)); // 获取命令行参数
const path = require('path');
const { build, context } = require('esbuild');
const { exec } = require('child_process');
const target = args._[0] || 'reactivity'; // 默认构建reactivity
const format = args.f || "global"; // 默认构建格式为global
const isTest = args.t ?? 0; // 默认不进行测试

const pkg = require(path.resolve(__dirname, `../packages/${target}/package.json`)); // 获取package.json
const outputFormat = format.startsWith("global") ? "iife" : format == "cjs" ? "cjs" : "esm"; // 根据格式设置输出格式
const entryFile = path.resolve(__dirname, `../packages/${target}/src/index.ts`); // 设置入口文件
const outFile = path.resolve(__dirname, `../packages/${target}/dist/${target}.${outputFormat}.js`); // 设置输出文件
console.log(args);
context({
  entryPoints: [entryFile],
  bundle: true,
  outfile: outFile,
  format: outputFormat,
  sourcemap: true,
  globalName: pkg.buildOptions?.name,
  platform: format === "cjs" ? "node" : "browser", // node环境
}).then((res) => {
  res.watch()
  // 启动服务器
  console.log("启动成功,数据监听中...");
  isTest && exec('node ./test/server.js', (error, stdout, stderr) => {
    console.log(`服务器输出: ${stdout}`);
    if (error) {
      console.error(`执行服务器脚本时出错: ${error}`);
      return;
    }
  });

}).catch((error) => {
  console.error("Build failed:---------------------------", error);
});
